<template>
  <div class="search-page">
    <div class="search-content">
      <div class="search-sidebar">
        <div class="filter-card">
          <div class="filter-title">筛选结果</div>
          <div class="filter-options">
            <div 
              v-for="tab in tabs" 
              :key="tab.value" 
              class="filter-option" 
              :class="{ active: activeTab === tab.value }" 
              @click="handleTabClick(tab.value)"
            >
              {{ tab.label }}
            </div>
          </div>
      </div>
      
        <div class="filter-card">
          <div class="filter-title">排序方式</div>
          <div class="filter-options">
            <div 
              v-for="sort in sortOptions" 
              :key="sort.value" 
              class="filter-option" 
              :class="{ active: sortBy === sort.value }" 
              @click="sortBy = sort.value; performSearch(true)"
            >
              {{ sort.label }}
            </div>
        </div>
      </div>
    </div>

      <div class="search-main">
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="5" animated />
      <el-skeleton :rows="5" animated />
      <el-skeleton :rows="5" animated />
    </div>

    <template v-else>
      <div v-if="searchResults.length === 0" class="empty-results">
        <el-empty 
          description="未找到相关结果" 
          :image-size="200"
        >
          <template #description>
            <p>未找到与"{{ searchKeyword }}"相关的结果</p>
                <p class="empty-suggestion">尝试使用其他关键词或浏览热门用户</p>
          </template>
          <el-button type="primary" @click="goToHome">返回首页</el-button>
        </el-empty>
      </div>

      <div v-else class="search-results">
        <div class="search-summary">
          找到 <strong>{{ totalResults }}</strong> 条与"<strong>{{ searchKeyword }}</strong>"相关的结果
        </div>
        
        <div v-if="activeTab === 'all' || activeTab === 'products'" class="results-section">
          <div v-if="activeTab === 'all'" class="section-header">
            <h2 class="section-title">商品</h2>
            <el-button link v-if="productResults.length > 4" @click="toggleSection('products')">
              {{ expandedSections.products ? '收起' : '查看更多' }} 
              <el-icon>
                <component :is="expandedSections.products ? 'ArrowUp' : 'ArrowRight'" />
              </el-icon>
            </el-button>
          </div>

          <div class="products-grid">
            <el-card 
              v-for="product in displayedProducts" 
              :key="product.id" 
              :body-style="{ padding: '0' }"
              class="product-card"
              shadow="hover"
              @click="goToProductDetail(product.id)"
            >
              <div class="product-image-container">
                <el-image :src="product.mainImage && product.mainImage.startsWith('http') ? product.mainImage : '/images/product/' + product.mainImage " fit="cover" class="product-image" />
                <div v-if="product.isHot" class="product-badge hot">热门</div>
                <div v-if="product.isNew" class="product-badge new">新品</div>
              </div>
              <div class="product-info">
                <h3 class="product-title">{{ product.name }}</h3>
                <div class="product-meta">
                  <span class="product-school">{{ product.school }}</span>
                  <span class="product-condition">{{ product.condition }}</span>
                </div>
                <div class="product-footer">
                  <div class="product-price">¥{{ product.price }}</div>
                  <div class="product-actions">
                    <el-button size="small" circle><el-icon><Star /></el-icon></el-button>
                    <el-button size="small" circle><el-icon><Message /></el-icon></el-button>
                  </div>
                </div>
              </div>
            </el-card>
          </div>
        </div>
        
        <div v-if="activeTab === 'all' || activeTab === 'requests'" class="results-section">
          <div v-if="activeTab === 'all'" class="section-header">
            <h2 class="section-title">求购</h2>
            <el-button link v-if="purchaseRequestResults.length > 4" @click="toggleSection('requests')">
              {{ expandedSections.requests ? '收起' : '查看更多' }}
              <el-icon>
                <component :is="expandedSections.requests ? 'ArrowUp' : 'ArrowRight'" />
              </el-icon>
            </el-button>
          </div>
          
          <div class="ios-requests-grid">
            <div 
              v-for="request in displayedPurchaseRequests" 
              :key="request.id"
              class="ios-request-card"
              @click="goToRequestDetail(request.id)"
            >
              <div class="request-header">
                <div class="user-info">
                  <el-avatar :size="40" :src=" '/images/user/' + request.userAvatar"></el-avatar>
                  <div class="user-details">
                    <div class="user-name"> {{ request.userName }} </div>
                    <div class="user-school">{{request.schoolName }}</div>
                  </div>
                </div>
                <div class="request-actions-top">
                  <div class="request-time">{{ calculateTimeSince(request.createTime) }}</div>
                  <el-button 
                    type="text" 
                    class="favorite-button" 
                    @click.stop="toggleFavorite(request)"
                    :class="{ 'is-favorite': request.isFavorite }"
                  >
                    <el-icon><Star /></el-icon>
                  </el-button>
                </div>
              </div>
              <div class="request-body">
                <h3 class="request-title">{{ request.title }}</h3>
                <p class="request-content">{{ request.description || request.content }}</p>
                <div class="request-tags">
                  <el-tag size="small" v-if="request.category || request.categoryName">{{ request.category || request.categoryName }}</el-tag>
                </div>
              </div>
              <div class="request-footer">
                <div class="request-budget">预算: ¥{{ request.budget }}</div>
                <div class="request-actions">
                  <el-button type="primary" size="small" @click="contactUser(request, $event)">联系</el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <div v-if="activeTab === 'all' || activeTab === 'schools'" class="results-section">
          <div v-if="activeTab === 'all'" class="section-header">
            <h2 class="section-title">学校</h2>
            <el-button link v-if="schoolResults.length > 3" @click="toggleSection('schools')">
              {{ expandedSections.schools ? '收起' : '查看更多' }}
              <el-icon>
                <component :is="expandedSections.schools ? 'ArrowUp' : 'ArrowRight'" />
              </el-icon>
            </el-button>
          </div>
          
          <div class="schools-grid">
            <el-card 
              v-for="school in displayedSchools" 
              :key="school.id" 
              class="school-card"
              shadow="hover"
              @click="goToSchool(school.id)"
            >
              <div class="school-image-container">
                <el-image :src="school.cover" fit="cover" class="school-image" />
              </div>
              <div class="school-info">
                <h3 class="school-name">{{ school.name }}</h3>
                <div class="school-meta">
                  <span>{{ school.productCount }}件商品</span>
                  <span>{{ school.memberCount }}位用户</span>
                </div>
                <p class="school-description">{{ school.description }}</p>
              </div>
            </el-card>
          </div>
        </div>
        
            <div v-if="activeTab === 'all' || activeTab === 'users'" class="results-section">
          <div v-if="activeTab === 'all'" class="section-header">
                <h2 class="section-title">用户</h2>
                <el-button link v-if="userResults.length > 4" @click="toggleSection('users')">
                  {{ expandedSections.users ? '收起' : '查看更多' }}
                  <el-icon>
                    <component :is="expandedSections.users ? 'ArrowUp' : 'ArrowRight'" />
                  </el-icon>
                </el-button>
          </div>
          
              <div class="users-grid">
            <el-card 
                  v-for="user in displayedUsers" 
                  :key="user.id" 
                  class="user-card"
              shadow="hover"
                  @click="goToUser(user.id)"
            >
                  <div class="user-content">
                    <el-avatar :size="90" :src="user.avatar && !user.avatar.startsWith('http') ? '/images/user/' + user.avatar : user.avatar || '/src/assets/avatar.png'" class="user-avatar"></el-avatar>
                    <div class="user-info">
                      <h3 class="user-name">{{ user.name || user.nickname }}</h3>
                      <div class="user-school">{{ user.school || user.schoolName }} <span v-if="user.major">({{ user.major }})</span></div>
                      <div class="user-meta">

                        <span v-if="user.credibility" class="user-credibility">信誉 {{ user.credibility }}</span>
                      </div>
                      <div v-if="user.introduction" class="user-introduction">{{ user.introduction }}</div>
                </div>
              </div>
            </el-card>
          </div>
        </div>
        
        <div v-if="shouldShowPagination" class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[12, 24, 36, 48]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalResults"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </template>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { 
  Search, ArrowRight, Star, Message, ArrowUp, ArrowDown,
  Reading, ShoppingBag, Suitcase, Football, Camera, Iphone, School, User 
} from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { search, searchProducts, searchSchools, searchUsers, searchPurchaseRequests } from '@/api/search';

const route = useRoute();
const router = useRouter();

// 搜索状态
const searchKeyword = ref('');
const activeTab = ref('all');
const sortBy = ref('newest');
const currentPage = ref(1);
const pageSize = ref(12);
const loading = ref(true);

// 标签选项
const tabs = [
  { label: '全部结果', value: 'all' },
  { label: '商品', value: 'products' },
  { label: '求购', value: 'requests' },
  { label: '学校', value: 'schools' },
  { label: '用户', value: 'users' }
];

// 排序选项
const sortOptions = [
  { label: '最新发布', value: 'newest' },
  { label: '价格从低到高', value: 'price_asc' },
  { label: '价格从高到低', value: 'price_desc' },
  { label: '最受欢迎', value: 'popular' }
];

// 搜索结果
const productResults = ref([]);
const purchaseRequestResults = ref([]);
const schoolResults = ref([]);
const userResults = ref([]);
const totalResults = ref(0);

// 控制展开/收起状态
const expandedSections = ref({
  products: false,
  requests: false,
  schools: false,
  users: false
});

// 处理标签点击
const handleTabClick = (tab) => {
  activeTab.value = tab;
  handleTabChange(tab);
};

// 执行搜索
const performSearch = async (updateUrl = true) => {
  if (!searchKeyword.value) return;
  
  if (isApiRequestInProgress.value) return; // 避免并发请求
  isApiRequestInProgress.value = true;
  loading.value = true;
  
  try {
    // 根据不同的标签调用不同的API
    let response;
    const params = {
      keyword: searchKeyword.value,
      page: currentPage.value,
      pageSize: pageSize.value,
      sortBy: sortBy.value
    };
    
    console.log('开始发送搜索请求, 参数:', params, '标签:', activeTab.value);
    
    if (activeTab.value === 'products') {
      console.log('调用商品搜索API');
      response = await searchProducts(params);
      console.log('商品搜索响应:', response);
      if (response.code === 200) {
        productResults.value = response.data.list || [];
        totalResults.value = response.data.total || 0;
      } else {
        ElMessage.error(response.msg || '获取商品数据失败');
        generateMockResults(); // 失败时使用模拟数据
        ElMessage.warning('获取数据失败，显示模拟数据');
      }
    } else if (activeTab.value === 'requests') {
      console.log('调用求购搜索API');
      response = await searchPurchaseRequests(params);
      console.log('求购搜索响应:', response);
      if (response.code === 200) {
        purchaseRequestResults.value = response.data.list || [];
        totalResults.value = response.data.total || 0;
      } else {
        ElMessage.error(response.msg || '获取求购数据失败');
        generateMockResults(); // 失败时使用模拟数据
        ElMessage.warning('获取数据失败，显示模拟数据');
      }
    } else if (activeTab.value === 'schools') {
      response = await searchSchools(params);
      if (response.code === 200) {
        schoolResults.value = response.data.list || [];
        totalResults.value = response.data.total || 0;
      } else {
        ElMessage.error(response.msg || '获取学校数据失败');
        generateMockResults(); // 失败时使用模拟数据
        ElMessage.warning('获取数据失败，显示模拟数据');
      }
    } else if (activeTab.value === 'users') {
      response = await searchUsers(params);
      if (response.code === 200) {
        userResults.value = response.data.list || [];
        totalResults.value = response.data.total || 0;
      } else {
        ElMessage.error(response.msg || '获取用户数据失败');
        generateMockResults(); // 失败时使用模拟数据
        ElMessage.warning('获取数据失败，显示模拟数据');
      }
    } else {
      // 'all' 标签 - 调用通用搜索
      response = await search({...params, tab: 'all'});
      if (response.code === 200) {
        productResults.value = response.data.products || [];
        purchaseRequestResults.value = response.data.purchaseRequests || [];
        schoolResults.value = response.data.schools || [];
        userResults.value = response.data.users || [];
        totalResults.value = 
          (response.data.totalProducts || 0) + 
          (response.data.totalPurchaseRequests || 0) +
          (response.data.totalSchools || 0) + 
          (response.data.totalUsers || 0);
      } else {
        ElMessage.error(response.msg || '搜索失败');
        generateMockResults(); // 失败时使用模拟数据
        ElMessage.warning('获取数据失败，显示模拟数据');
      }
    }
    
    // 先完成API调用后再更新URL，避免触发watch导致重复请求
    if (updateUrl) {
    router.push({ 
      query: { 
        ...route.query,
        keyword: searchKeyword.value,
        tab: activeTab.value,
        page: currentPage.value
      }
    });
    }
  } catch (error) {
    console.error('搜索出错:', error);
    ElMessage.error('网络异常，服务器未响应');
    generateMockResults(); // 失败时使用模拟数据
    ElMessage.warning('获取数据失败，显示模拟数据');
  } finally {
    loading.value = false;
    isApiRequestInProgress.value = false; // 重置标志
  }
};

// 生成模拟数据
const generateMockResults = () => {
  const keyword = searchKeyword.value.toLowerCase();
  
  // 模拟产品数据
  const mockProducts = [];
  const productNames = [
    `${keyword}手机`, `二手${keyword}`, `全新${keyword}`, 
    `${keyword}电脑`, `${keyword}书籍`, `${keyword}用品`
  ];
  const conditions = ['全新', '几乎全新', '轻微使用', '正常使用'];
  const schools = ['北京大学', '清华大学', '中国人民大学', '北京师范大学', '北京航空航天大学'];
  
  for (let i = 1; i <= 15; i++) {
    mockProducts.push({
      id: i,
      name: productNames[i % productNames.length] + ` ${i}`,
      price: Math.floor(Math.random() * 1000) + 50,
      image: '/src/assets/placeholder.png',
      school: schools[i % schools.length],
      condition: conditions[i % conditions.length],
      isHot: Math.random() > 0.8,
      isNew: Math.random() > 0.7
    });
  }
  productResults.value = mockProducts;
  
  // 模拟求购数据
  const mockPurchaseRequests = [];
  const requestTitles = [
    `求购${keyword}`, `寻找${keyword}`, `想要${keyword}`, 
    `求${keyword}`, `收${keyword}`, `有偿求${keyword}`
  ];
  const categories = ['电子产品', '书籍教材', '生活用品', '服装鞋帽', '运动器材'];
  
  for (let i = 1; i <= 15; i++) {
    mockPurchaseRequests.push({
      id: i,
      title: requestTitles[i % requestTitles.length] + ` ${i}`,
      content: `我想求购一个${keyword}${i}，要求成色良好，价格合理，有意者请联系我。`,
      budget: Math.floor(Math.random() * 1000) + 100,
      category: categories[i % categories.length],
      time: `${Math.floor(Math.random() * 24)}小时前`,
      user: {
        id: i,
        name: ['张同学', '李同学', '王同学', '刘同学', '赵同学'][i % 5],
        avatar: i % 2 === 0 ? '/images/user/kele_1747181243866.jpg' : '/images/user/de097bd8-c059-4114-b83e-ec5703b790d2.jpg',
        school: ['北京大学', '清华大学', '中国人民大学', '北京师范大学', '北京航空航天大学'][i % 5]
      },
      isFavorite: Math.random() > 0.8
    });
  }
  purchaseRequestResults.value = mockPurchaseRequests;
  
  // 模拟学校数据
  const mockSchools = [];
  for (let i = 1; i <= 5; i++) {
    mockSchools.push({
      id: i,
      name: schools[i - 1],
      image: '/src/assets/school-placeholder.png',
      productCount: Math.floor(Math.random() * 1000) + 100,
      memberCount: Math.floor(Math.random() * 5000) + 500,
      description: `${schools[i - 1]}是中国知名高校，校内二手交易活跃，商品种类丰富。`
    });
  }
  schoolResults.value = mockSchools;
  
  // 模拟用户数据
  const mockUsers = [
    { 
      id: 1, 
      name: '张同学', 
      nickname: '张同学', 
      avatar: '/images/user/kele_1747181243866.jpg', 
      productCount: 32, 
      school: '北京大学', 
      schoolName: '北京大学',
      introduction: '计算机科学专业学生，热爱二手交易',
      major: '计算机科学',
      credibility: 95
    },
    { 
      id: 2, 
      name: '李同学', 
      nickname: '李同学', 
      avatar: '/images/user/de097bd8-c059-4114-b83e-ec5703b790d2.jpg', 
      productCount: 18, 
      school: '清华大学', 
      schoolName: '清华大学',
      introduction: '电子工程专业，专注二手数码产品',
      major: '电子工程',
      credibility: 98
    },
    { 
      id: 3, 
      name: '王同学', 
      nickname: '王同学', 
      avatar: '/src/assets/avatar-placeholder.png', 
      productCount: 27, 
      school: '中国人民大学', 
      schoolName: '中国人民大学',
      introduction: '经济学专业，二手书籍交易达人',
      major: '经济学',
      credibility: 92
    },
    { 
      id: 4, 
      name: '刘同学', 
      nickname: '刘同学', 
      avatar: '/src/assets/avatar-placeholder.png', 
      productCount: 9, 
      school: '北京师范大学', 
      schoolName: '北京师范大学',
      introduction: '教育学专业，专注二手教材',
      major: '教育学',
      credibility: 90
    },
    { 
      id: 5, 
      name: '赵同学', 
      nickname: '赵同学', 
      avatar: '/src/assets/avatar-placeholder.png', 
      productCount: 14, 
      school: '北京航空航天大学', 
      schoolName: '北京航空航天大学',
      introduction: '航空航天专业，热衷分享二手实验器材',
      major: '航空航天',
      credibility: 97
    }
  ];
  userResults.value = mockUsers;
  
  // 设置总结果数
  totalResults.value = activeTab.value === 'all' 
    ? mockProducts.length + mockPurchaseRequests.length + mockSchools.length + mockUsers.length
    : activeTab.value === 'products' 
      ? mockProducts.length 
      : activeTab.value === 'requests'
        ? mockPurchaseRequests.length
        : activeTab.value === 'schools'
          ? mockSchools.length
          : mockUsers.length;
};

// 监听路由参数变化
const isApiRequestInProgress = ref(false); // 添加标志，避免重复请求

watch(() => route.query, (newQuery) => {
  if (newQuery.keyword && !isApiRequestInProgress.value) {
    searchKeyword.value = newQuery.keyword;
    if (newQuery.tab && ['all', 'products', 'schools', 'users'].includes(newQuery.tab)) {
      activeTab.value = newQuery.tab;
    }
    if (newQuery.page) {
      currentPage.value = parseInt(newQuery.page) || 1;
    }
    performSearch(false); // 不需要更新URL，因为已经是从URL更新状态
  }
}, { immediate: true, deep: true });

// 计算属性
const searchResults = computed(() => {
  switch (activeTab.value) {
    case 'products':
      return productResults.value;
    case 'requests':
      return purchaseRequestResults.value;
    case 'schools':
      return schoolResults.value;
    case 'users':
      return userResults.value;
    case 'all':
    default:
      return [...productResults.value, ...purchaseRequestResults.value, ...schoolResults.value, ...userResults.value];
  }
});

const displayedProducts = computed(() => {
  return activeTab.value === 'all' 
    ? (expandedSections.value.products ? productResults.value : productResults.value.slice(0, 4))
    : productResults.value;
});

const displayedPurchaseRequests = computed(() => {
  return activeTab.value === 'all' 
    ? (expandedSections.value.requests ? purchaseRequestResults.value : purchaseRequestResults.value.slice(0, 4))
    : purchaseRequestResults.value;
});

const displayedSchools = computed(() => {
  return activeTab.value === 'all' 
    ? (expandedSections.value.schools ? schoolResults.value : schoolResults.value.slice(0, 3))
    : schoolResults.value;
});

const displayedUsers = computed(() => {
  return activeTab.value === 'all' 
    ? (expandedSections.value.users ? userResults.value : userResults.value.slice(0, 4))
    : userResults.value;
});

const shouldShowPagination = computed(() => {
  return activeTab.value !== 'all' && totalResults.value > pageSize.value;
});

// 处理分页大小变化
const handleSizeChange = (size) => {
  pageSize.value = size;
  performSearch(true);
};

// 处理页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page;
  performSearch(true);
};

// 处理搜索
const handleSearch = () => {
  if (searchKeyword.value.trim()) {
    currentPage.value = 1;
    performSearch(true);
  }
};

// 处理标签切换
const handleTabChange = (tab) => {
  currentPage.value = 1;
  performSearch(true);
};

// 查看更多/收起结果
const toggleSection = (tab) => {
  if (activeTab.value === 'all') {
    expandedSections.value[tab] = !expandedSections.value[tab];
  } else {
    activeTab.value = tab;
    performSearch(true);
  }
};

// 获取用户图标
const getUserIcon = (userId) => {
  return 'User';
};

// 导航函数
const goToProductDetail = (productId) => {
  router.push(`/product/${productId}`);
};

const goToSchool = (schoolId) => {
  router.push(`/school/${schoolId}`);
};

const goToUser = (userId) => {
  // 使用与聊天界面相同的访客模式访问个人中心
  router.push(`/user/center?userId=${userId}`);
};

const goToHome = () => {
  router.push('/');
};

const goToRequestDetail = (requestId) => {
  router.push(`/request/${requestId}`);
};

// 组件挂载时，如果有搜索关键词则执行搜索
onMounted(() => {
  if (route.query.keyword) {
    searchKeyword.value = route.query.keyword;
    performSearch(false); // 不需要更新URL，因为已经是从URL加载
  } else {
    loading.value = false;
  }
});

// 添加收藏/取消收藏
const toggleFavorite = (request, e) => {
  // 阻止事件冒泡
  if (e) e.stopPropagation();
  
  // 检查请求对象是否有效
  if (!request) {
    ElMessage.warning('无法操作该求购信息');
    return;
  }
  
  // 在实际应用中，这里应该调用API
  request.isFavorite = !request.isFavorite;
  ElMessage.success(request.isFavorite ? '已添加到收藏' : '已取消收藏');
};

// 联系用户
const contactUser = async (request, e) => {
  // 阻止事件冒泡，避免触发卡片点击
  if (e) e.stopPropagation();
  
  try {
    // 检查用户是否已登录
    const token = localStorage.getItem('token');
    const userInfo = localStorage.getItem('userInfo');
    if (!token || !userInfo) {
      ElMessage.warning('请先登录后再联系求购者');
      router.push('/login?redirect=' + encodeURIComponent(router.currentRoute.value.fullPath));
      return;
    }
    
    const userId = JSON.parse(userInfo).id;
    if (!userId) {
      ElMessage.warning('无法获取用户信息，请重新登录');
      return;
    }

    // 获取求购发布者的ID
    const requesterId = request.userId || (request.user ? request.user.id : null);
    if (!requesterId) {
      ElMessage.error('无法获取求购者信息');
      return;
    }
    
    if (userId === requesterId) {
      ElMessage.info('您不能和自己聊天哦');
      return;
    }
    
    // 发送联系请求
    const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080/api';
    const response = await fetch(`${API_BASE_URL}/requests/${request.id}/contact`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      body: JSON.stringify({
        message: '您好，我看到了您的求购信息，想和您详细聊一下。'
      })
    });
    
    // 获取响应数据
    const data = await response.json();
    console.log('联系求购者响应:', data);
    
    // 根据后端返回的错误码来判断
    if (!data) {
      ElMessage.error('网络异常，请稍后重试');
      return;
    }
    
    // 只有当code为200时才视为成功
    if (data.code !== 200) {
      // 根据不同错误码显示不同错误信息
      switch (data.code) {
        case 400:
          ElMessage.error(data.message || '请求参数错误');
          break;
        case 401:
          ElMessage.error('用户未登录或登录已过期');
          break;
        case 403:
          ElMessage.error('您没有权限联系该求购者');
          break;
        case 404:
          ElMessage.error('求购信息不存在');
          break;
        case 409:
          ElMessage.error(data.message || '不能联系自己');
          break;
        case 500:
          ElMessage.error('服务器内部错误，请稍后重试');
          break;
        default:
          // 始终优先使用后端返回的错误信息
          ElMessage.error(data.message || `联系失败(${data.code})`);
      }
      // 无论什么错误都不跳转
      return;
    }
    
    // 联系成功，显示成功消息
    ElMessage.success(data.message || '已成功发起联系');
    
    // 从后端响应中获取会话相关信息
    const responseData = data.data || {};
    
    // 跳转到聊天页面，使用后端返回的会话ID或对话相关信息
    if (responseData.conversationId || responseData.chatId) {
      router.push({
        path: '/chat',
        query: {
          conversationId: responseData.conversationId || responseData.chatId,
          // 后端可能还会返回其他有用的参数，也一并传递
          sellerId: responseData.sellerId || requesterId,
          requestId: request.id
        }
      });
    } else {
      // 如果后端没有返回会话ID，则使用用户ID跳转
      router.push({
        path: '/chat',
        query: {
          partnerId: requesterId,
          requestId: request.id
        }
      });
    }
  } catch (error) {
    console.error('联系用户失败:', error);
    ElMessage.error('联系用户失败，请稍后重试');
  }
};

// 计算发布时间到现在的时间差
const calculateTimeSince = (dateString) => {
  if (!dateString) return '未知时间';
  
  const now = new Date();
  const date = new Date(dateString);
  const seconds = Math.floor((now - date) / 1000);
  
  // 时间差小于60秒
  if (seconds < 60) {
    return '刚刚';
  }
  
  // 时间差小于1小时
  const minutes = Math.floor(seconds / 60);
  if (minutes < 60) {
    return `${minutes}分钟前`;
  }
  
  // 时间差小于24小时
  const hours = Math.floor(minutes / 60);
  if (hours < 24) {
    return `${hours}小时前`;
  }
  
  // 时间差小于30天
  const days = Math.floor(hours / 24);
  if (days < 30) {
    return `${days}天前`;
  }
  
  // 时间差小于12个月
  const months = Math.floor(days / 30);
  if (months < 12) {
    return `${months}个月前`;
  }
  
  // 时间差大于等于12个月
  const years = Math.floor(months / 12);
  return `${years}年前`;
};
</script>

<style scoped>
.search-page {
  max-width: 90%;
  margin: 0 auto;
  padding: 20px;
}

.search-content {
  display: flex;
  gap: 24px;
}

.search-sidebar {
  width: 220px;
  flex-shrink: 0;
}

.search-main {
  flex: 1;
}

.filter-card {
  background-color: #fff;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  margin-bottom: 16px;
}

.filter-title {
  padding: 12px 16px;
  font-size: 16px;
  font-weight: 500;
  color: #333;
  border-bottom: 1px solid #f0f0f0;
  background-color: #fafafa;
}

.filter-options {
  padding: 8px;
}

.filter-option {
  padding: 10px 16px;
  border-radius: 8px;
  margin: 4px 0;
  cursor: pointer;
  transition: all 0.2s;
  color: #606266;
  font-size: 14px;
}

.filter-option:hover {
  background-color: #f5f7fa;
}

.filter-option.active {
  background-color: #007AFF;
  color: white;
  font-weight: 500;
}

.sort-container {
  padding: 8px 16px 16px;
}

.sort-select {
  width: 100%;
}

.sort-select :deep(.el-input__wrapper) {
  border-radius: 8px;
  padding: 0 12px;
  background-color: #F2F2F7;
  border: 1px solid rgba(0, 0, 0, 0.05);
  color: #8E8E93;
}

.sort-select :deep(.el-input__wrapper:hover) {
  background-color: #E5E5EA;
  border-color: rgba(0, 0, 0, 0.08);
  transform: translateY(-1px);
}

.sort-select :deep(.el-select__popper) {
  border-radius: 8px;
}

.sort-select :deep(.el-select-dropdown__item) {
  padding: 0 12px;
  height: 34px;
  line-height: 34px;
}

.search-summary {
  margin-bottom: 20px;
  font-size: 16px;
  color: #606266;
}

.loading-container {
  margin-bottom: 20px;
}

.empty-results {
  padding: 40px 0;
  text-align: center;
}

.empty-suggestion {
  color: #909399;
  margin-top: 8px;
}

.results-section {
  margin-bottom: 32px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.section-title {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.products-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 16px;
}

.product-card {
  cursor: pointer;
  transition: transform 0.2s;
  border-radius: 16px;
  overflow: hidden;
}

.product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
}

.product-image-container {
  position: relative;
  height: 220px;
  background-color: #f5f7fa;
  border-radius: 16px 16px 0 0;
  overflow: hidden;
}

.product-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-badge {
  position: absolute;
  top: 10px;
  left: 10px;
  padding: 4px 10px;
  border-radius: 10px;
  font-size: 12px;
  font-weight: 500;
  color: white;
}

.product-badge.hot {
  background-color: #ff6b6b;
}

.product-badge.new {
  background-color: #4cd964;
}

.product-info {
  padding: 12px;
}

.product-title {
  margin: 0 0 10px;
  font-size: 16px;
  font-weight: 500;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #303133;
}

.product-meta {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  font-size: 13px;
  color: #909399;
}

.product-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.product-price {
  font-size: 18px;
  font-weight: 600;
  color: #f56c6c;
}

.product-actions {
  display: flex;
  gap: 5px;
}

.product-actions :deep(.el-button) {
  background: #F2F2F7;
  border: 1px solid rgba(0, 0, 0, 0.05);
  color: #8E8E93;
  transition: all 0.3s ease;
}

.product-actions :deep(.el-button:hover) {
  background: #E5E5EA;
  border-color: rgba(0, 0, 0, 0.08);
  transform: translateY(-1px);
}

.requests-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 16px;
}

.request-card {
  cursor: pointer;
  transition: transform 0.2s;
  border-radius: 16px;
  overflow: hidden;
}

.request-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
}

.schools-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
}

.school-card {
  cursor: pointer;
  transition: transform 0.2s;
  overflow: hidden;
  border-radius: 16px;
}

.school-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
}

.school-image-container {
  height: 150px;
  background-color: #f5f7fa;
  border-radius: 16px 16px 0 0;
  overflow: hidden;
}

.school-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.school-info {
  padding: 15px;
}

.school-name {
  margin: 0 0 10px;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.school-meta {
  display: flex;
  gap: 20px;
  margin-bottom: 10px;
  font-size: 14px;
  color: #909399;
}

.school-description {
  margin: 0;
  color: #606266;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.users-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 16px;
}

.user-card {
  cursor: pointer;
  transition: transform 0.2s;
  border-radius: 16px;
  overflow: hidden;
}

.user-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
}

.user-content {
  padding: 20px;
  display: flex;
  flex-direction: row;
  align-items: center;
  text-align: left;
}

.user-avatar {
  margin-right: 15px;
  flex-shrink: 0;
}

.user-info {
  flex: 1;
  min-width: 0;
}

.user-name {
  margin: 0 0 5px;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.user-school {
  font-size: 14px;
  color: #606266;
  margin-bottom: 5px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.user-meta {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  color: #909399;
  margin-bottom: 5px;
}

.user-credibility {
  color: #67C23A;
  font-weight: 500;
}

.user-introduction {
  font-size: 13px;
  color: #909399;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  margin-top: 5px;
}

.pagination-container {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}

.pagination-container .el-pagination .el-pager li {
  border-radius: 8px;
}

@media (max-width: 768px) {
  .search-content {
    flex-direction: column;
  }
  
  .search-sidebar {
    width: 100%;
    margin-bottom: 20px;
  }
  
  .products-grid {
    grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
  }
  
  .schools-grid {
    grid-template-columns: 1fr;
  }
  
  .users-grid {
    grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
  }
}

/* 全局按钮样式覆盖 */
:deep(.el-button--default) {
  background: #F2F2F7;
  border: 1px solid rgba(0, 0, 0, 0.05);
  color: #8E8E93;
  transition: all 0.3s ease;
}

:deep(.el-button--default:hover) {
  background: #E5E5EA;
  border-color: rgba(0, 0, 0, 0.08);
  transform: translateY(-1px);
}

:deep(.el-button--primary) {
  background: #007AFF;
  border: none;
  color: white;
  transition: all 0.3s ease;
}

:deep(.el-button--primary:hover) {
  background: #0062CC;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 122, 255, 0.3);
}

.ios-requests-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.ios-request-card {
  background: #ffffff;
  border-radius: 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  transition: all 0.3s ease;
  cursor: pointer;
}

.ios-request-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
}

.request-header {
  padding: 15px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #f0f0f0;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-details {
  margin-left: 10px;
}

.user-name {
  font-weight: 500;
  font-size: 15px;
  color: #333;
  margin-bottom: 2px;
}

.user-school {
  font-size: 13px;
  color: #909399;
}

.request-actions-top {
  display: flex;
  align-items: center;
}

.request-time {
  font-size: 13px;
  color: #909399;
  margin-right: 10px;
}

.favorite-button {
  padding: 6px;
  color: #909399;
}

.favorite-button.is-favorite {
  color: #ff9900;
}

.request-body {
  padding: 15px 20px;
}

.request-title {
  font-size: 20px;
  font-weight: 700;
  color: #333;
  margin-bottom: 10px;
}

.request-content {
  font-size: 14px;
  color: #606266;
  margin-bottom: 15px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.request-tags {
  margin-bottom: 15px;
}

.request-footer {
  padding: 15px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-top: 1px solid #f0f0f0;
}

.request-budget {
  font-weight: 700;
  color: #f56c6c;
  font-size: 18px;
}
</style> 